var store=require("store");
var pop = require("pop/pop.js");
var uploadData = JSON.parse($.base64.decode(store.get().upload));
//console.error(uploadData);
accessid= uploadData.accessKeyId;
accesskey= uploadData.accessKeySecret;
host = uploadData.endpoint.split("//")[0]+"//"+uploadData.inputBucket+"."+uploadData.endpoint.split("//")[1];
var file_count = 1;
var _count=0;
var reality_count=0;

g_dirname = 'information_video/'
g_object_name = ''
g_object_name_type = 'local_name'
now = timestamp = Date.parse(new Date()) / 1000; 

var policyText = {
    "expiration": "2020-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
    "conditions": [
    ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
    ]
};

var policyBase64 = $.base64.encode(JSON.stringify(policyText))
message = policyBase64
var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, { asBytes: true }) ;
var signature = Crypto.util.bytesToBase64(bytes);

function check_object_radio() {
    var tt = document.getElementsByName('myradio');
    for (var i = 0; i < tt.length ; i++ )
    {
        if(tt[i].checked)
        {
            g_object_name_type = tt[i].value;
            break;
        }
    }
}

function get_dirname()
{
    dir = document.getElementById("dirname").value;
    if (dir != '' && dir.indexOf('/') != dir.length - 1)
    {
        dir = dir + '/'
    }
    //alert(dir)
    g_dirname = dir
}

function random_string(len) {
　　len = len || 32;
　　var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';   
　　var maxPos = chars.length;
　　var pwd = '';
　　for (i = 0; i < len; i++) {
    　　pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function calculate_object_name(filename)
{
    if (g_object_name_type == 'local_name')
    {
    	suffix = get_suffix(filename);
    	var __name = g_dirname+ new Date().getTime() +"__"+filename;
        g_object_name = __name;
    }
    else if (g_object_name_type == 'random_name')
    {
        suffix = get_suffix(filename)
        g_object_name = g_dirname + random_string(10) + suffix
    }
    return ''
}

function get_uploaded_object_name(filename)
{
    if (g_object_name_type == 'local_name')
    {
        tmp_name = g_object_name
        //tmp_name = tmp_name.replace("${filename}", filename);
        return tmp_name
    }
    else if(g_object_name_type == 'random_name')
    {
        return g_object_name
    }
}

function set_upload_param(up, filename, ret)
{
   // g_object_name = g_object_name;
    if (filename != '') {
        suffix = get_suffix(filename)
        calculate_object_name(filename)
    }
    new_multipart_params = {
        'key' : g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid, 
        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
        'signature': signature,
    };

    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });

    up.start();
}

var uploader = new plupload.Uploader({
	runtimes : 'html5,flash,silverlight,html4',
	browse_button : 'selectfiles', 
    multi_selection: false,
	container: document.getElementById('container'),
	flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
	silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
    url : 'http://oss.aliyuncs.com',
	//文件过滤规则
    filters: {
        mime_types: [ 
            {title: "Video files", extensions: "avi,mp4,wmv,mov,FLV"}
        ],
        max_file_size: '1024mb', 
        prevent_duplicates: false 
    },
	init: {
		PostInit: function() {
			document.getElementById('ossfile').innerHTML = '';
			//document.getElementById('postfiles').onclick = function() {
	        //   set_upload_param(uploader, '', false);
	            return false;
			//};
		},

		FilesAdded: function(up, files) {
			_count+=files.length;
			if(_count<file_count){
				plupload.each(files, function(file) {
					document.getElementById('ossfile').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b>'
					+'<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>'
					+'</div>';
				});
				set_upload_param(uploader, '', false);
				reality_count = _count;
			}else if(_count==file_count){
				$("#container_vidoe").hide();
				plupload.each(files, function(file) {
					document.getElementById('ossfile').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b>'
					+'<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>'
					+'</div>';
				});
				set_upload_param(uploader, '', false);
				reality_count = _count;
			}else{
				//console.error("u2",_count,file_count);
				_count = reality_count;
				pop.tip("超过上传视频数量");
				return;
			}
			
		},

		BeforeUpload: function(up, file) {
            //check_object_radio();
            //get_dirname();
            set_upload_param(up, file.name, true);
        },

		UploadProgress: function(up, file) {
			var d = document.getElementById(file.id);
			if(d){
				d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
	            var prog = d.getElementsByTagName('div')[0];
				var progBar = prog.getElementsByTagName('div')[0]
				progBar.style.width= 2*file.percent+'px';
				progBar.setAttribute('aria-valuenow', file.percent);
			}
		},

		FileUploaded: function(up, file, info) {
            if (info.status == 200)
            {
                document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '上传成功:' + get_uploaded_object_name(file.name);
                
                if($("#ossfile").attr("fileName")){
                	$("#ossfile").attr("fileName",$("#ossfile").attr("fileName")+","+get_uploaded_object_name(file.name));
                }else{
                	$("#ossfile").attr("fileName",get_uploaded_object_name(file.name));
                }
            }
            else
            {
                document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
                _count -=1;
                $("#container_vidoe").show();
            } 
		},

		Error: function(up, err) {
			//document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
			_count -=1;
			$("#container_vidoe").show();
			if(err.code===-601){
				pop.tip("只允许上传AVI、 MP4、 WMV 、 MOV、FLV格式的视频文件!");
			}else if(err.code===-600){
				pop.tip("所选文件大小超过1G，请重新选择!");	
			}else{
				pop.tip(err.response);
			}
			return;
			
		}
	}
});

var uploader_init = {
	_init : function(opt){
		//console.error(opt)
		uploader.init();
		if(opt && opt!=""){
			file_count = opt;
		}
	},
	setFile_count :function(opt){
		file_count = opt;
	}
}
module.exports = uploader_init;
//uploader.init();
